package com.guoxin.jiyin.boot;


import com.guoxin.jiyin.enums.ApiCode;
import com.guoxin.jiyin.exception.BlockChainException;
import com.guoxin.jiyin.model.ApiResult;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Created by lgh on 2016/1/12.
 */
public class ApiHandlerExceptionResolver implements HandlerExceptionResolver {
    private Logger logger = LogManager.getLogger(ApiHandlerExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        String requestURI = request.getRequestURI().substring(request.getContextPath().length());
        ModelAndView mv = new ModelAndView();
        ApiResult result = new ApiResult();

        try {
            throw ex;
        } catch (BlockChainException bc) {
            result.setCode(ApiCode.BLOCK_CHAIN_ERROR.getValue());
            result.setMessage(ApiCode.BLOCK_CHAIN_ERROR.getName());
            logger.error(requestURI, ex);
        } catch (Exception e) {
            result.setCode(ApiCode.REQUEST_ERROR.getValue());
            result.setMessage(ApiCode.REQUEST_ERROR.getName());
            logger.error(requestURI, e);
        }

        mv.addObject("__realResult", result);
        MappingJackson2JsonView jsonView = new MappingJackson2JsonView();

        jsonView.setContentType("application/json;charset=UTF-8");
        jsonView.setModelKey("__realResult");
        jsonView.setExtractValueFromSingleKeyModel(true);
        mv.setView(jsonView);
        return mv;
    }
}
